package com.changgou.goods.service.impl;

import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.SpecMapper;
import com.changgou.goods.dao.TemplateMapper;
import com.changgou.goods.pojo.Category;
import com.changgou.goods.pojo.Spec;
import com.changgou.goods.service.SpecService;
import com.changgou.goods.service.TemplateService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class SpecServiceImpl implements SpecService {

    @Autowired
    private SpecMapper specMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Spec> findAll() {
        return specMapper.selectAll();
    }

    @Override
    public void add(Spec spec) {
        specMapper.insert(spec);
    }

    @Override
    public List<Spec> findList(Spec spec) {
        Example example = createExample(spec);
        List<Spec> specs = specMapper.selectByExample(example);
        return specs;
    }

    @Override
    public PageInfo<Spec> findPage(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        PageInfo<Spec> pageInfo = new PageInfo<>(specMapper.selectAll());
        return pageInfo;
    }

    @Override
    public PageInfo<Spec> findPage(Integer page, Integer size, Spec spec) {
        Example example = createExample(spec);
        PageHelper.startPage(page, size);
        PageInfo<Spec> pageInfo = new PageInfo<>(specMapper.selectByExample(example));
        return pageInfo;
    }

    @Override
    public List<Spec> findByCategoryId(Integer id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        Spec spec = new Spec();
        spec.setTemplateId(category.getTemplateId());
        return specMapper.select(spec);
    }

    @Override
    public Spec findById(Integer id) {
        return specMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Spec spec) {
        specMapper.updateByPrimaryKey(spec);
    }

    @Override
    public void delete(Integer id) {
        specMapper.deleteByPrimaryKey(id);
    }

    /****
     * 构建查询对象
     * @param spec
     * @return
     */
    private Example createExample(Spec spec) {
        Example example = new Example(Spec.class);
        Example.Criteria criteria = example.createCriteria();
        if (spec != null) {
            if (StringUtils.isNotEmpty(spec.getName())) {
                criteria.andLike("name", "%" + spec.getName() + "%");
            }
            if (StringUtils.isNotEmpty(spec.getOptions())) {
                criteria.andEqualTo("options", spec.getOptions());
            }
        }
        return example;
    }
}
